package com.wt;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.view.KeyEvent;
import android.media.ToneGenerator;
import android.text.Editable;
import android.content.Intent;
import android.telecom.TelecomManager;
import android.widget.ListView;
import android.content.Context;
import android.widget.AdapterView;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import android.widget.TextView;
import android.view.ViewGroup;
import android.telephony.TelephonyManager;
import android.widget.BaseAdapter;

import com.android.contacts.common.util.Constants;
import com.android.contacts.common.CallUtil;
import com.android.dialer.util.DialerUtils;
import com.android.phone.common.dialpad.DialpadView;
import com.android.phone.common.dialpad.DialpadKeyButton;
import com.android.dialer.R;

import com.android.dialer.SpecialCharSequenceMgr;
import android.text.TextWatcher;

import com.android.dialer.calllog.CallLogActivity;

import com.goodocom.gocsdk.IGocsdkExt;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.content.ComponentName;
import android.util.Log;
import android.widget.Toast;

public class WtDialtactsActivity extends Activity{
	private EditText mDigits;
	private DialpadView mDialpadView;
	private View mDelete;
	private ListView mDialpadChooser;
	private DialpadChooserAdapter mDialpadChooserAdapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.wt_dialtacts_activity);
		mDialpadView = (DialpadView)findViewById(R.id.dialpad_view);
		mDialpadView.setCanDigitsBeEdited(true);
		mDigits = mDialpadView.getDigits();
		mDigits.addTextChangedListener(mTextWatcher);
		
		mDelete = mDialpadView.getDeleteButton();
		if (mDelete != null) {
		    mDelete.setOnClickListener(mOnClickListener);
		    mDelete.setOnLongClickListener(mOnLongClickListener);
		}

		View dialButtonBt = findViewById(R.id.dial_button_bt);
		dialButtonBt.setOnClickListener(mOnClickListener);

		View dialButton = findViewById(R.id.dial_button);
		dialButton.setOnClickListener(mOnClickListener);
		
		View calllogBtn = findViewById(R.id.wt_calllog_btn);
		calllogBtn.setOnClickListener(mOnClickListener);
		
		configureKeypadListeners();

		mDialpadChooser = (ListView) findViewById(R.id.dialpadChooser);
		mDialpadChooser.setOnItemClickListener(new AdapterView.OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				DialpadChooserAdapter.ChoiceItem item = (DialpadChooserAdapter.ChoiceItem) parent.getItemAtPosition(position);
				int itemId = item.id;
				switch (itemId) {
					case DialpadChooserAdapter.DIALPAD_CHOICE_USE_DTMF_DIALPAD:
						// Log.i(TAG, "DIALPAD_CHOICE_USE_DTMF_DIALPAD");
						// Fire off an intent to go back to the in-call UI
						// with the dialpad visible.
						returnToInCallScreen(true);
						break;

					case DialpadChooserAdapter.DIALPAD_CHOICE_RETURN_TO_CALL:
						// Log.i(TAG, "DIALPAD_CHOICE_RETURN_TO_CALL");
						// Fire off an intent to go back to the in-call UI
						// (with the dialpad hidden).
						returnToInCallScreen(false);
						break;

					case DialpadChooserAdapter.DIALPAD_CHOICE_ADD_NEW_CALL:
						// Log.i(TAG, "DIALPAD_CHOICE_ADD_NEW_CALL");
						// Ok, guess the user really did want to be here (in the
						// regular Dialer) after all.  Bring back the normal Dialer UI.
						showDialpadChooser(false);
						break;

					default:
						break;
				}
			}
		});

		if (mCallStateReceiver == null) {
			IntentFilter callStateIntentFilter = new IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
			mCallStateReceiver = new CallStateReceiver();
			this.registerReceiver(mCallStateReceiver, callStateIntentFilter);
		}

/*
		mDialChannelChooseView = findViewById(R.id.dial_channel_choose);
		mDialChannelChooseView.setOnClickListener(mDialOnClickListener);
		View dialLocalView = findViewById(R.id.dial_channel_local);
		dialLocalView.setOnClickListener(mDialOnClickListener);
		View dialBtView = findViewById(R.id.dial_channel_bt);
		dialBtView.setOnClickListener(mDialOnClickListener);
*/
		Intent intent = new Intent();
		intent.setComponent(new ComponentName("com.goodocom.gocsdkfinal","com.goodocom.gocsdkfinal.service.GocsdkExtService"));
		mMyConnection = new MyConnection();
		bindService(intent, mMyConnection, Context.BIND_AUTO_CREATE);
    	}

	@Override
	public void onResume() {
		super.onResume();
		showDialpadChooser(isPhoneInUse());
	}

	@Override
	public void onDestroy(){
		super.onDestroy();
		this.unregisterReceiver(mCallStateReceiver);
	}

    private void configureKeypadListeners() {
        final int[] buttonIds = new int[] {R.id.one, R.id.two, R.id.three, R.id.four, R.id.five,
                R.id.six, R.id.seven, R.id.eight, R.id.nine, R.id.star, R.id.zero, R.id.pound};

        DialpadKeyButton dialpadKey;

        for (int i = 0; i < buttonIds.length; i++) {
            dialpadKey = (DialpadKeyButton) findViewById(buttonIds[i]);
            dialpadKey.setOnClickListener(mOnClickListener);
        }

        // Long-pressing one button will initiate Voicemail.
        final DialpadKeyButton one = (DialpadKeyButton) findViewById(R.id.one);
        one.setOnLongClickListener(mOnLongClickListener);

        // Long-pressing zero button will enter '+' instead.
        final DialpadKeyButton zero = (DialpadKeyButton) findViewById(R.id.zero);
        zero.setOnLongClickListener(mOnLongClickListener);
    }
	
    private static final int TONE_LENGTH_INFINITE = -1;
    private void keyPressed(int keyCode) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_1:
                playTone(ToneGenerator.TONE_DTMF_1, TONE_LENGTH_INFINITE);
                break;
            case KeyEvent.KEYCODE_2:
                playTone(ToneGenerator.TONE_DTMF_2, TONE_LENGTH_INFINITE);
                break;
            case KeyEvent.KEYCODE_3:
                playTone(ToneGenerator.TONE_DTMF_3, TONE_LENGTH_INFINITE);
                break;
            case KeyEvent.KEYCODE_4:
                playTone(ToneGenerator.TONE_DTMF_4, TONE_LENGTH_INFINITE);
                break;
            case KeyEvent.KEYCODE_5:
                playTone(ToneGenerator.TONE_DTMF_5, TONE_LENGTH_INFINITE);
                break;
            case KeyEvent.KEYCODE_6:
                playTone(ToneGenerator.TONE_DTMF_6, TONE_LENGTH_INFINITE);
                break;
            case KeyEvent.KEYCODE_7:
                playTone(ToneGenerator.TONE_DTMF_7, TONE_LENGTH_INFINITE);
                break;
            case KeyEvent.KEYCODE_8:
                playTone(ToneGenerator.TONE_DTMF_8, TONE_LENGTH_INFINITE);
                break;
            case KeyEvent.KEYCODE_9:
                playTone(ToneGenerator.TONE_DTMF_9, TONE_LENGTH_INFINITE);
                break;
            case KeyEvent.KEYCODE_0:
                playTone(ToneGenerator.TONE_DTMF_0, TONE_LENGTH_INFINITE);
                break;
            case KeyEvent.KEYCODE_POUND:
                playTone(ToneGenerator.TONE_DTMF_P, TONE_LENGTH_INFINITE);
                break;
            case KeyEvent.KEYCODE_STAR:
                playTone(ToneGenerator.TONE_DTMF_S, TONE_LENGTH_INFINITE);
                break;
            default:
                break;
        }

        //mHaptic.vibrate();
        KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
        mDigits.onKeyDown(keyCode, event);

        // If the cursor is at the end of the text we hide it.
        final int length = mDigits.length();
        if (length == mDigits.getSelectionStart() && length == mDigits.getSelectionEnd()) {
            mDigits.setCursorVisible(false);
        }
    }

    private void playTone(int tone, int durationMs) {
    }
	
	private View.OnClickListener mOnClickListener = new View.OnClickListener(){
		@Override
		public void onClick(View view){
	            switch (view.getId()) {
	                case R.id.one: {
	                    keyPressed(KeyEvent.KEYCODE_1);
	                    break;
	                }
	                case R.id.two: {
	                    keyPressed(KeyEvent.KEYCODE_2);
	                    break;
	                }
	                case R.id.three: {
	                    keyPressed(KeyEvent.KEYCODE_3);
	                    break;
	                }
	                case R.id.four: {
	                    keyPressed(KeyEvent.KEYCODE_4);
	                    break;
	                }
	                case R.id.five: {
	                    keyPressed(KeyEvent.KEYCODE_5);
	                    break;
	                }
	                case R.id.six: {
	                    keyPressed(KeyEvent.KEYCODE_6);
	                    break;
	                }
	                case R.id.seven: {
	                    keyPressed(KeyEvent.KEYCODE_7);
	                    break;
	                }
	                case R.id.eight: {
	                    keyPressed(KeyEvent.KEYCODE_8);
	                    break;
	                }
	                case R.id.nine: {
	                    keyPressed(KeyEvent.KEYCODE_9);
	                    break;
	                }
	                case R.id.zero: {
	                    keyPressed(KeyEvent.KEYCODE_0);
	                    break;
	                }
	                case R.id.pound: {
	                    keyPressed(KeyEvent.KEYCODE_POUND);
	                    break;
	                }
	                case R.id.star: {
	                    keyPressed(KeyEvent.KEYCODE_STAR);
	                    break;
	                }
	                case R.id.deleteButton: {
	                    keyPressed(KeyEvent.KEYCODE_DEL);
	                    break;
	                }
	                case R.id.dial_button: {
	                    handleDialButtonPressed();
	                    break;
	                }
	                case R.id.wt_calllog_btn: {
	                    showCallHistory();
	                    break;
	                }
	                case R.id.dial_button_bt: {
	                    doDialBt();
	                    break;
	                }
	                default: {
	                    break;
	                }
	            }
		}
	};

    public void showCallHistory() {
        final Intent intent = new Intent(this, CallLogActivity.class);
        startActivity(intent);
    }

    private void handleDialButtonPressed() {
        /// M: [Ip Dial] add ip dial
        handleDialButtonPressed(Constants.DIAL_NUMBER_INTENT_NORMAL);
    }

    private boolean isDigitsEmpty() {
        return mDigits.length() == 0;
    }
	
    public void handleDialButtonClickWithEmptyDigits() {
    }
	
    private void handleDialButtonPressed(int type) {
        if (isDigitsEmpty()) { // No number entered.
            handleDialButtonClickWithEmptyDigits();
        } else {
            final String number = mDigits.getText().toString();

            // "persist.radio.otaspdial" is a temporary hack needed for one carrier's automated
            // test equipment.
            // TODO: clean it up.
            /*if (number != null
                    && !TextUtils.isEmpty(mProhibitedPhoneNumberRegexp)
                    && number.matches(mProhibitedPhoneNumberRegexp)) {
                if (getActivity() != null) {
                    DialogFragment dialogFragment = ErrorDialogFragment.newInstance(
                            R.string.dialog_phone_call_prohibited_message);
                    dialogFragment.show(getFragmentManager(), "phone_prohibited_dialog");
                }

                // Clear the digits just in case.
                clearDialpad();
            } else */{
            /*
            	  Log.i("hcj.GocsdkExtService", "handleDialButtonPressed mBtConnected="+mBtConnected);
            	  if(mBtConnected){
			mDialNumber = number;
			mDialChannelChooseView.setVisibility(View.VISIBLE);
			return;
            	  }
		*/
                final Intent intent;
                /** M: [Ip Dial] check the type of call @{ */
                if (type != Constants.DIAL_NUMBER_INTENT_NORMAL) {
                    intent = CallUtil.getCallIntent(CallUtil.getCallUri(number),
                            "com.wt.WtDialtactsActivity",
                            type);
                } else {
                    intent = CallUtil.getCallIntent(number,
                            "com.wt.WtDialtactsActivity");
                }
                /** @} */
                DialerUtils.startActivityWithErrorToast(this, intent);
            }
        }
    }

	private View.OnLongClickListener mOnLongClickListener = new View.OnLongClickListener(){
		@Override
		public boolean onLongClick(View view){
			final int id = view.getId();
			switch (id) {
				case R.id.deleteButton: {
					final Editable digits = mDigits.getText();
					digits.clear();
					break;
				}
			}
			return true;
		}
	};

	private TextWatcher mTextWatcher = new TextWatcher(){
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {

		}

		@Override
		public void onTextChanged(CharSequence input, int start, int before, int changeCount) {

		}

		@Override
		public void afterTextChanged(Editable input) {
			if (SpecialCharSequenceMgr.handleChars(WtDialtactsActivity.this, input.toString(), mDigits)) {
				// A special sequence was entered, clear the digits
				mDigits.getText().clear();
			}

			if (isDigitsEmpty()) {
				mDigits.setCursorVisible(false);
			}
		}
	};

	private void showDialpadChooser(boolean enabled) {
		mDialpadView.setVisibility(enabled ? View.GONE : View.VISIBLE);
		mDialpadChooser.setVisibility(enabled ? View.VISIBLE : View.GONE);
		if(enabled){
			if (mDialpadChooserAdapter == null) {
				mDialpadChooserAdapter = new DialpadChooserAdapter(this);
			}
			mDialpadChooser.setAdapter(mDialpadChooserAdapter);
		}
	}

    private void returnToInCallScreen(boolean showDialpad) {
        getTelecomManager().showInCallScreen(showDialpad);

        // Finally, finish() ourselves so that we don't stay on the
        // activity stack.
        // Note that we do this whether or not the showCallScreenWithDialpad()
        // call above had any effect or not!  (That call is a no-op if the
        // phone is idle, which can happen if the current call ends while
        // the dialpad chooser is up.  In this case we can't show the
        // InCallScreen, and there's no point staying here in the Dialer,
        // so we just take the user back where he came from...)
        finish();
    }
	
    public boolean isPhoneInUse() {
        return getTelecomManager().isInCall();
    }

    private TelecomManager getTelecomManager() {
        return (TelecomManager) getSystemService(Context.TELECOM_SERVICE);
    }

    private static class DialpadChooserAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        // Simple struct for a single "choice" item.
        static class ChoiceItem {
            String text;
            Bitmap icon;
            int id;

            public ChoiceItem(String s, Bitmap b, int i) {
                text = s;
                icon = b;
                id = i;
            }
        }

        // IDs for the possible "choices":
        static final int DIALPAD_CHOICE_USE_DTMF_DIALPAD = 101;
        static final int DIALPAD_CHOICE_RETURN_TO_CALL = 102;
        static final int DIALPAD_CHOICE_ADD_NEW_CALL = 103;

        private static final int NUM_ITEMS = 3;
        private ChoiceItem mChoiceItems[] = new ChoiceItem[NUM_ITEMS];

        public DialpadChooserAdapter(Context context) {
            // Cache the LayoutInflate to avoid asking for a new one each time.
            mInflater = LayoutInflater.from(context);

            // Initialize the possible choices.
            // TODO: could this be specified entirely in XML?

            // - "Use touch tone keypad"
            mChoiceItems[0] = new ChoiceItem(
                    context.getString(R.string.dialer_useDtmfDialpad),
                    BitmapFactory.decodeResource(context.getResources(),
                                                 R.drawable.ic_dialer_fork_tt_keypad),
                    DIALPAD_CHOICE_USE_DTMF_DIALPAD);

            // - "Return to call in progress"
            mChoiceItems[1] = new ChoiceItem(
                    context.getString(R.string.dialer_returnToInCallScreen),
                    BitmapFactory.decodeResource(context.getResources(),
                                                 R.drawable.ic_dialer_fork_current_call),
                    DIALPAD_CHOICE_RETURN_TO_CALL);

            // - "Add call"
            mChoiceItems[2] = new ChoiceItem(
                    context.getString(R.string.dialer_addAnotherCall),
                    BitmapFactory.decodeResource(context.getResources(),
                                                 R.drawable.ic_dialer_fork_add_call),
                    DIALPAD_CHOICE_ADD_NEW_CALL);
        }

        @Override
        public int getCount() {
            return NUM_ITEMS;
        }

        /**
         * Return the ChoiceItem for a given position.
         */
        @Override
        public Object getItem(int position) {
            return mChoiceItems[position];
        }

        /**
         * Return a unique ID for each possible choice.
         */
        @Override
        public long getItemId(int position) {
            return position;
        }

        /**
         * Make a view for each row.
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // When convertView is non-null, we can reuse it (there's no need
            // to reinflate it.)
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.dialpad_chooser_list_item, null);
            }

            TextView text = (TextView) convertView.findViewById(R.id.text);
            text.setText(mChoiceItems[position].text);

            ImageView icon = (ImageView) convertView.findViewById(R.id.icon);
            icon.setImageBitmap(mChoiceItems[position].icon);

            return convertView;
        }
    }
	
    private CallStateReceiver mCallStateReceiver;

    private class CallStateReceiver extends BroadcastReceiver {
        /**
         * Receive call state changes so that we can take down the
         * "dialpad chooser" if the phone becomes idle while the
         * chooser UI is visible.
         */
        @Override
        public void onReceive(Context context, Intent intent) {
            // Log.i(TAG, "CallStateReceiver.onReceive");
            String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
            if ((TextUtils.equals(state, TelephonyManager.EXTRA_STATE_IDLE) ||
                    TextUtils.equals(state, TelephonyManager.EXTRA_STATE_OFFHOOK))
                    && isDialpadChooserVisible()) {
                // Log.i(TAG, "Call ended with dialpad chooser visible!  Taking it down...");
                // Note there's a race condition in the UI here: the
                // dialpad chooser could conceivably disappear (on its
                // own) at the exact moment the user was trying to select
                // one of the choices, which would be confusing.  (But at
                // least that's better than leaving the dialpad chooser
                // onscreen, but useless...)
                showDialpadChooser(false);
            }
        }
    }
	
    private boolean isDialpadChooserVisible() {
        return mDialpadChooser.getVisibility() == View.VISIBLE;
    }



	private IGocsdkExt mGocsdkService;
	private MyConnection mMyConnection;
	//private boolean mBtConnected;
	
	private class MyConnection implements ServiceConnection {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mGocsdkService = IGocsdkExt.Stub.asInterface(service);
			/*
			try{
				mBtConnected = mGocsdkService.isBtConnected();
			}catch(Exception e){
				Log.i("hcj.GocsdkExtService", "onServiceConnected e="+e);
			}
			Log.i("hcj.GocsdkExtService", "onServiceConnected mBtConnected="+mBtConnected);
			*/
		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			mGocsdkService = null;
			Log.i("hcj.GocsdkExtService", "onServiceDisconnected mGocsdkService="+mGocsdkService);
		}
	}
/*
	private View mDialChannelChooseView;
	private View.OnClickListener mDialOnClickListener = new View.OnClickListener(){
		@Override
		public void onClick(View v){
			int id = v.getId();
			if(id == R.id.dial_channel_local){
				doDialLocal();
			}else if(id == R.id.dial_channel_bt){
				doDialBt();
			}else if(id == R.id.dial_channel_choose){
				return;
			}
			mDialChannelChooseView.setVisibility(View.GONE);
		}
	};

	private String mDialNumber;
	private void doDialLocal(){
                final Intent intent;
                intent = CallUtil.getCallIntent(mDialNumber,
                            "com.wt.WtDialtactsActivity");
                DialerUtils.startActivityWithErrorToast(this, intent);
	}
*/
	private void doDialBt(){
		if(!canBtDial()){
			Toast.makeText(this, R.string.warning_bt_device_not_connect, Toast.LENGTH_SHORT).show();
			return;
		}
		if (isDigitsEmpty()) { // No number entered.
			handleDialButtonClickWithEmptyDigits();
		} else {
			final String number = mDigits.getText().toString();
			
			try{
				mGocsdkService.dial(number);
			}catch(Exception e){
				Log.i("hcj.GocsdkExtService", "onServiceConnected e="+e);
			}
		}
	}

	private boolean canBtDial(){
		if(mGocsdkService == null){
			return false;
		}
		boolean connected = false;
		try{
			connected = mGocsdkService.isBtConnected();
		}catch(Exception e){
			Log.i("hcj.GocsdkExtService", "onServiceConnected e="+e);
		}
		return connected;
	}
}
